package server;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.net.BindException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;

import model.WavToArffParser;
import model.WavToInstanceParser;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;

import vwg.AppArguments;
import weka.core.Instance;
import weka.core.Instances;
import classification.Classifier;

public class Main {

	private static int PORT_NUMBER = 8987;
	private static Logger LOGGER = Logger.getLogger(Main.class.toString());

	public static void main(String[] args) throws Exception {

		Server server = new Server(PORT_NUMBER);

		try {

			AppArguments appArgs = new AppArguments();
			appArgs.parseArgs(args);

			Instances instances = WavToArffParser.parseToArff(
					System.getProperty("user.dir") + appArgs.getRelSrc(),
					System.getProperty("user.dir") + appArgs.getRelTarget(),
					appArgs.isClassified(), appArgs.isCustomExtractor(),
					appArgs.getAttributesCount());

			BufferedReader reader = new BufferedReader(new FileReader(
					"src/main/resources/12-wszyscy.arff"));

			instances = new Instances(reader);
			if (instances.classIndex() == -1) {
				instances.setClassIndex(instances.numAttributes() - 1);
			}

			Classifier classifier = null;
			try {
				classifier = Classifier.getClassifier(instances);
				Desktop.getDesktop().browse(
						new URI("http://localhost:" + PORT_NUMBER));
			} catch (Exception e) {
				e.printStackTrace();
			}

			ContextHandler contextPage = new ContextHandler();
			contextPage.setContextPath("/");
			contextPage.setHandler(new MainResourceHandler());

			ContextHandler contextRest = new ContextHandler();
			contextRest.setContextPath("/rest");
			contextRest.setHandler(new RestHandler(classifier));

			ContextHandlerCollection contexts = new ContextHandlerCollection();
			contexts.setHandlers(new Handler[] { contextPage, contextRest });

			server.setHandler(contexts);
			server.start();
			server.join();

			LOGGER.log(Level.INFO, "New instance of server is ready.");

		} catch (BindException e) {

			LOGGER.log(Level.INFO, "Server is already running.");

		}

	}

}
